package com.maserb.monitor.remote;

import com.maserb.monitor.ApplicationUtils;
import com.maserb.monitor.service.schoolStudent.AttendanceRecordService;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.thymeleaf.spring5.context.SpringContextUtils;

public class AFSTServerHandler extends ChannelHandlerAdapter {

    @Autowired
    AttendanceRecordService attendanceRecordService;

    public AFSTServerHandler() {
        attendanceRecordService = ApplicationUtils.getBean(AttendanceRecordService.class);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 用于获取客户端发来的数据信息
        AFSTMessageProtocol body = (AFSTMessageProtocol) msg;
        if ("08".equals(body.getFuncNo())) {
            SchoolRecordRequestEntity record = new SchoolRecordRequestEntity();
            record.fromBytes(body.getContent());
            System.out.println(record);

            //判断是否学生卡有效并且存入数据库
            Integer result = attendanceRecordService.saveRecord(record);
            response(result, ctx, body);
        } else {
            response(1, ctx, body);
        }
    }

    public void response(Integer validFlag, ChannelHandlerContext ctx, AFSTMessageProtocol body) {
        // 会写数据给客户端
        SchoolRecordResponseEntity recordResponse = new SchoolRecordResponseEntity(validFlag);
        byte[] responseData = recordResponse.getBytes();
        AFSTMessageProtocol response = new AFSTMessageProtocol(responseData.length, body.getFuncNo(), body.getSeqNo(),
                responseData);
        // 当服务端完成写操作后，关闭与客户端的连接
        ctx.writeAndFlush(response);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
